<script setup lang="ts">
// 引入vue相关
import {nextTick, onMounted, reactive, ref, Ref, computed} from "vue";
// 引入element-plus组件
import {ElMessage, FormInstance} from "element-plus";
// 引入自定义弹框组件
import SysDialog from "@/components/dialog/SysDialog.vue";
// 引入弹框组件的Hooks封装属性和方法
import useDialog from "@/hooks/useDialog.ts";
// 获取全局实例
import useInstance from "@/hooks/useInstance.ts";
// 引入统一格式化工具
import { formatPrice } from '@/utils/formatter'
// 错误处理工具
import { handleError } from '@/utils/errorHandler'
// 获取全局 global
const {global} = useInstance()

// 项目api
import {getProjectDocumentListApi} from "@/api/project";
import {ProjectDocument, ProjectDocumentListParam} from "@/api/project/type";
// 仓库api
import {getListApi} from "@/api/software";
import {SoftwareWarehouse, SoftwareWarehouseListParam} from "@/api/software/type";
// 软件核价计划api
import {softwarePlanListParam, ExportFieldInfo, ExportRequest} from '@/api/softwarePricingPlan/type.ts'
import {querySoftwarePlanListApi,deleteApi,updateStatusApi,importSoftwarePricingPlanApi,exportSoftwarePricingPlanApi,downloadSoftwarePricingPlanTemplateApi, exportCustomSoftwarePricingPlanApi, getExportFieldsApi, batchUpdateStatusApi, batchCopyApi} from '@/api/softwarePricingPlan/index.ts'
import ArchiveSelector from "@/components/common/ArchiveSelector.vue";

// 引入图标
import { Plus, Setting, Search, Check, InfoFilled, Close, Download, Switch, Refresh, Upload, Delete, CopyDocument } from '@element-plus/icons-vue';
// 引入vue-router
import { useRouter } from 'vue-router'
// 获取路由实例
const router = useRouter()

// 定义表单ref实例
const form = ref<FormInstance>()
// 文件上传ref
const fileInputRef = ref<HTMLInputElement>()

//定义表单校验规则
const rules = {
}

// 表格数据和总条数和表格高度和加载效果
const dataList = ref<any[]>([])  // 表格列表数据
const total = ref(0)  // 分页器总条数
const loading = ref(false)    // 表格加载效果
const tableHeight = ref(0)    // 表格内容高度

// 批量操作相关
const selectedRows = ref<any[]>([])
const tableRef = ref()

// 批量复制相关
const batchCopyVisible = ref(false)
const targetProjectSelectorVisible = ref(false)
const selectedTargetProject = ref<ProjectDocument | null>(null)

// 定义搜索表单数据
const searchForm = ref<softwarePlanListParam>({
  projectId: undefined,
  repositoryId:  undefined,
  activate: undefined,
  page: 1,
  limit: 10,
})

// 仓库选择器相关数据
const warehouseSelectorVisible = ref(false);
const selectedWarehouse = ref<SoftwareWarehouse | null>(null);

// 项目选择器相关数据
const projectSelectorVisible = ref(false);
const selectedProject = ref<ProjectDocument | null>(null);

// 仓库选择器搜索字段配置
const warehouseSearchFields = [
  {label: '仓库名称', prop: 'name', type: 'input' as const}
];

// 仓库选择器表格列配置
const warehouseTableColumns = [
  {prop: 'name', label: '仓库名称', width: 280},
  {prop: 'remark', label: '备注'}
];
// 项目状态映射
const statusOptions = [
  {value: 0, label: '进行中'},
  {value: 1, label: '已完成'},
  {value: 2, label: '已暂停'},
  {value: 3, label: '已取消'}
];

// 项目选择器搜索字段配置
const projectSearchFields = [
  {label: '项目名称', prop: 'name', type: 'input' as const},
  {label: '项目编号', prop: 'code', type: 'input' as const},
  {label: '客户名称', prop: 'customer', type: 'input' as const},
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions
  }
];

// 项目选择器表格列配置
const projectTableColumns = [
  {prop: 'name', label: '项目名称', width: 250},
  {prop: 'code', label: '项目编号', width: 250},
  {prop: 'customer', label: '客户名称', width: 250},
  {prop: 'manager', label: '项目经理', width: 200}
];

// 表格列配置
const tableColumns = ref([
  { prop: 'id', label: 'ID', width: 80 },
  { prop: 'projectName', label: '项目名称', width: 180 },
  { prop: 'repositoryName', label: '仓库名称', width: 180 },
  { prop: 'projectAmount', label: '项目金额', width: 120 },
  { prop: 'wmsAmount', label: 'WMS金额', width: 120 },
  { prop: 'wcsAmount', label: 'WCS金额', width: 120 },
  { prop: 'interfaceAmount', label: '接口金额', width: 120 },
  { prop: 'totalImplementationPrice', label: '实施总价', width: 120 },
  { prop: 'materialPrice', label: '物料价格', width: 120 },
  { prop: 'totalPrice', label: '总价', width: 150 },
  { prop: 'createTime', label: '创建时间', width: 180 },
  { prop: 'status', label: '状态', width: 100 },
]);

// 获取仓库列表数据的API方法
const getWarehouseList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: SoftwareWarehouseListParam = {
      name: params.name,
      page: params.page || 1,
      limit: params.limit || 10
    };

    // 调用仓库列表API - 使用真实API
    return await getListApi(queryParams);
  } catch (error) {
    console.error('获取仓库列表失败:', error);
    return {data: {list: [], total: 0}};
  }
};

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10
    };

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams);
  } catch (error) {
    console.error('获取项目列表失败:', error);
    return {data: {list: [], total: 0}};
  }
};

// 处理仓库选择确认
const handleWarehouseSelect = (warehouse: SoftwareWarehouse) => {
  selectedWarehouse.value = warehouse;
  console.log('选择的仓库:', warehouse);
  searchForm.value.repositoryId = warehouse.id || 0;
};

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project;
  console.log('选择的项目:', project);
  searchForm.value.projectId = project.id || 0;
};

// 打开仓库选择器
const openWarehouseSelector = () => {
  warehouseSelectorVisible.value = true;
};

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true;
};

// 获取数据列表方法
const getDataList = async () => {
  loading.value = true
  isDataLoaded.value = false // 数据加载开始，设置标志位为false
  try {
    const res = await querySoftwarePlanListApi(searchForm.value)
    dataList.value = res.data.list
    total.value = res.data.total
    // 使用nextTick确保DOM更新完成后再设置标志位
    await nextTick()
    isDataLoaded.value = true // 数据加载完成，设置标志位为true
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  searchForm.value.page = 1
  getDataList()
}

// 搜索重置方法
const handleReset = () => {
  searchForm.value = {
    projectId: undefined,
    repositoryId: undefined,
    activate: undefined,
    page: 1,
    limit: 10
  }
  selectedProject.value = null
  selectedWarehouse.value = null
  getDataList()
}

// 修改软件核价单的状态
const updateStatus = reactive({
  id: undefined as number | undefined,
  activate: undefined as boolean | undefined
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 自定义导出相关
const exportFieldList = ref<ExportFieldInfo[]>([])
const selectedExportFields = ref<string[]>([])
const exportDialog = reactive({
  visible: false
})
const fieldSearchText = ref('')

// 过滤后的导出字段列表
const filteredExportFields = computed(() => {
  if (!fieldSearchText.value) {
    return exportFieldList.value
  }
  return exportFieldList.value.filter(field =>
    field.displayName.toLowerCase().includes(fieldSearchText.value.toLowerCase()) ||
    field.fieldName.toLowerCase().includes(fieldSearchText.value.toLowerCase())
  )
})

// 激活 失效
const activateChange = async (val: boolean, id: number) => {
  // 如果数据还没加载完成，不执行更新操作
  if (!isDataLoaded.value) return
  
  updateStatus.id = id
  updateStatus.activate = val
  try {
    await updateStatusApi({ id, activate: val ? 1 : 0 })
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 分页变化
const handleCurrentChange = (page: number) => {
  searchForm.value.page = page
  getDataList()
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  searchForm.value.limit = size
  searchForm.value.page = 1
  getDataList()
}

// 删除数据方法
const handleDelete = async (id: number) => {
  // 检查对应记录的状态
  const record = dataList.value.find(item => item.id === id)
  if (record && (record.activate !== 1)) {
    ElMessage.warning('该软件核价计划已失效，不允许删除')
    return
  }
  
  try {
    await global.$myConfirm('确定要删除该核价单吗，是否继续?')
    await deleteApi(id)
    ElMessage.success('删除成功')
    getDataList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  // 检查选中的记录中是否有已失效的
  const invalidRecords = selectedRows.value.filter(item => item.activate !== 1)
  if (invalidRecords.length > 0) {
    ElMessage.warning(`选中的记录中有${invalidRecords.length}条已失效，不允许删除操作`)
    return
  }

  try {
    await global.$myConfirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗？`)
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    // 这里需要后端提供批量删除API，暂时使用循环删除
    for (const id of ids) {
      await deleteApi(id)
    }
    ElMessage.success('批量删除成功')
    getDataList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  }
}

// 批量失效
const handleBatchDeactivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要失效的记录')
    return
  }
  
  try {
    await global.$myConfirm(`确定要将选中的${selectedRows.value.length}条记录设为失效吗？`)
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 0 })
    ElMessage.success('批量失效成功')
    getDataList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    console.error('批量失效失败:', error)
    ElMessage.error('批量失效失败')
  }
}

// 批量生效
const handleBatchActivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要生效的记录')
    return
  }
  
  try {
    await global.$myConfirm(`确定要将选中的${selectedRows.value.length}条记录设为生效吗？`)
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 1 })
    ElMessage.success('批量生效成功')
    getDataList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    console.error('批量生效失败:', error)
    ElMessage.error('批量生效失败')
  }
}

// 打开批量复制弹窗
const openBatchCopyDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要复制的记录')
    return
  }
  
  // 允许复制失效数据，复制后自动生效
  
  batchCopyVisible.value = true
}

// 关闭批量复制弹窗
const closeBatchCopyDialog = () => {
  batchCopyVisible.value = false
  selectedTargetProject.value = null
}

// 打开目标项目选择器
const openTargetProjectSelector = () => {
  targetProjectSelectorVisible.value = true
}

// 处理目标项目选择
const handleTargetProjectSelect = (project: ProjectDocument) => {
  selectedTargetProject.value = project
  console.log('选择的目标项目:', project)
}

// 确认批量复制
const confirmBatchCopy = async () => {
  if (!selectedTargetProject.value) {
    ElMessage.warning('请选择目标项目')
    return
  }
  
  try {
    await global.$myConfirm(`确定要将选中的${selectedRows.value.length}条软件核价方案复制到项目"${selectedTargetProject.value.name}"吗？`)
    
    const sourceIds = selectedRows.value.map(row => row.id).filter(id => id)
    await batchCopyApi({
      sourceIds,
      targetProjectId: selectedTargetProject.value.id!
    })
    
    ElMessage.success(`成功复制${sourceIds.length}条软件核价方案`)
    closeBatchCopyDialog()
    await getDataList()
    
    // 清空选中状态
    selectedRows.value = []
    tableRef.value?.clearSelection()
  } catch (error) {
    handleError(error, '批量复制失败')
  }
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'primary' // 进行中
    case 1: return 'success' // 已完成
    case 2: return 'warning' // 已暂停
    case 3: return 'danger'  // 已取消
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : '-'
}

// 查看
const handleView = (id: number) => {
  router.push(`/softwareForm/${id}?mode=view`)
}

// 编辑
const handleEdit=(id:number)=>{
  // 检查对应记录的状态
  const record = dataList.value.find(item => item.id === id)
  if (record && (record.activate !== 1)) {
    ElMessage.warning('该软件核价计划已失效，不允许编辑')
    return
  }
  router.push(`/softwareForm/${id}`)
}
// 新增
const handleAdd=()=>{
  router.push(`/softwareForm`)
}

// 文件上传处理
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  
  if (!file) return
  
  const loading = ElMessage({
    message: '正在导入数据...',
    type: 'info',
    duration: 0
  })

  importSoftwarePricingPlanApi(file)
    .then((res: any) => {
      loading.close()
      ElMessage.success('导入成功')
      getDataList() // 刷新列表
      // 清空文件选择
      if (fileInputRef.value) {
        fileInputRef.value.value = ''
      }
    })
    .catch((error: any) => {
      loading.close()
      handleError(error, '导入失败')
      
      // 清空文件选择
      if (fileInputRef.value) {
        fileInputRef.value.value = ''
      }
    })
}

// 导出数据
const handleExport = async () => {
  try {
    loading.value = true
    searchForm.value.limit = 9999

    await exportSoftwarePricingPlanApi(searchForm.value)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    loading.value = true
    await downloadSoftwarePricingPlanTemplateApi()
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  } finally {
    loading.value = false
  }
}

// 获取可导出字段列表
const getExportFieldList = async () => {
  try {
    const res = await getExportFieldsApi()
    if (res.code === 200) {
      exportFieldList.value = res.data
    }
  } catch (error) {
    console.error('获取导出字段列表失败:', error)
  }
}

// 打开自定义导出弹窗
const openExportDialog = () => {
  exportDialog.visible = true
  // 默认选中所有字段
  selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
}

// 关闭自定义导出弹窗
const closeExportDialog = () => {
  exportDialog.visible = false
  fieldSearchText.value = ''
}

// 切换字段选中状态
const toggleField = (fieldName: string) => {
  const index = selectedExportFields.value.indexOf(fieldName)
  if (index > -1) {
    selectedExportFields.value.splice(index, 1)
  } else {
    selectedExportFields.value.push(fieldName)
  }
}

// 全选/取消全选导出字段
const handleSelectAllFields = (checked: boolean) => {
  if (checked) {
    selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
  } else {
    selectedExportFields.value = []
  }
}

// 确认自定义导出
const confirmCustomExport = async () => {
  if (selectedExportFields.value.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }
  
  try {
    loading.value = true
    // 移除分页参数，确保导出所有数据
    const { page, limit, ...exportParams } = searchForm.value
    
    // 检查是否有查询条件
    const hasConditions = Object.keys(exportParams).some(key => {
      const value = (exportParams as any)[key]
      return value !== undefined && value !== null && value !== ''
    })
    
    if (hasConditions) {
      console.log('自定义导出-按查询条件导出数据:', exportParams)
      ElMessage.info('正在导出符合当前查询条件的数据...')
    } else {
      console.log('自定义导出-导出全部数据')
      ElMessage.info('正在导出全部数据...')
    }
    
    await exportCustomSoftwarePricingPlanApi({
      fields: selectedExportFields.value,
      searchParam: exportParams as any
    })
    
    ElMessage.success('导出成功')
    closeExportDialog()
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取列表数据
onMounted(() => {
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 获取数据列表
  getDataList()
  // 获取导出字段列表
  getExportFieldList()
})

// 新增triggerFileUpload方法
const triggerFileUpload = () => {
  fileInputRef.value?.click()
}
</script>

<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <!-- 搜索表单 -->
        <div class="search-form-section">
          <el-form :inline="true" :model="searchForm" ref="queryForm" class="demo-form-inline">
            <el-form-item label="项目信息">
              <el-input
                :model-value="selectedProject ? selectedProject.name : ''"
                placeholder="请选择项目"
                readonly
                class="selector-input"
              >
                <template #append>
                  <el-button @click="openProjectSelector" v-permission="['softwarePlan:view']">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="仓库信息">
              <el-input
                :model-value="selectedWarehouse ? selectedWarehouse.name : ''"
                placeholder="请选择仓库"
                readonly
                class="selector-input"
              >
                <template #append>
                  <el-button @click="openWarehouseSelector" v-permission="['softwarePlan:view']">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select 
                v-model="searchForm.activate"
                placeholder="是否生效"
                clearable
                filterable
                style="width: 120px"
              >
                <el-option label="生效" :value="1" />
                <el-option label="失效" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" @click="handleSearch" class="search-btn" v-permission="['softwarePlan:view']">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="handleReset" class="reset-btn" v-permission="['softwarePlan:view']">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons-section">
          <div class="button-group primary-actions">
            <!-- 主要操作按钮 -->
          </div>
          
          <div class="button-group secondary-actions">
            <el-button type="success" @click="handleAdd" class="add-btn" v-permission="['softwarePlan:edit']">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
            <el-button 
              type="danger" 
              @click="handleBatchDelete" 
              class="batch-delete-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['softwarePlan:edit']"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="warning" 
              @click="handleBatchDeactivate" 
              class="batch-deactivate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['softwarePlan:edit']"
            >
              <el-icon><Close /></el-icon>
              批量失效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="success" 
              @click="handleBatchActivate" 
              class="batch-activate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['softwarePlan:edit']"
            >
              <el-icon><Check /></el-icon>
              批量生效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="info" 
              @click="openBatchCopyDialog" 
              class="batch-copy-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['softwarePlan:edit']"
            >
              <el-icon><CopyDocument /></el-icon>
              批量复制 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button type="info" @click="handleDownloadTemplate" class="template-btn" v-permission="['softwarePlan:view']">
              <el-icon><Download /></el-icon>
              下载模板
            </el-button>
            <el-button type="warning" @click="triggerFileUpload" class="import-btn" v-permission="['softwarePlan:edit']">
              <el-icon><Upload /></el-icon>
              导入
            </el-button>
            <el-button type="primary" @click="handleExport" class="export-btn" v-permission="['softwarePlan:view']">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button type="primary" @click="openExportDialog" class="custom-export-btn" v-permission="['softwarePlan:view']">
              <el-icon><Setting /></el-icon>
              自定义导出
            </el-button>
            
            <!-- 隐藏的文件输入框 -->
            <input
              type="file"
              ref="fileInputRef"
              style="display: none"
              accept=".xlsx, .xls"
              @change="handleFileChange"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgba(255, 255, 255, 0.7)"
        style="width: 100%"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="activate" label="状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.activate ? 'success' : 'danger'">
            {{ scope.row.activate ? '生效' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column prop="projectName" label="项目名称" width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="repositoryName" label="仓库名称" width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="projectAmount" label="项目金额" width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.projectAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wmsAmount" label="WMS金额" width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.wmsAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wcsAmount" label="WCS金额" width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.wcsAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="interfaceAmount" label="接口金额" width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.interfaceAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalImplementationPrice" label="实施总价" width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.totalImplementationPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="materialPrice" label="物料价格" width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.materialPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="总价" width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatPrice(scope.row.totalPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.createName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="更新人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.updateName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360" align="center" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="info" size="small" @click="handleView(scope.row.id)" plain v-permission="['softwarePlan:view']">
                查看
              </el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row.id)" :disabled="scope.row.activate !== 1" v-permission="['softwarePlan:edit']">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" :disabled="scope.row.activate !== 1" v-permission="['softwarePlan:edit']">
                删除
              </el-button>
              <!-- <el-switch v-model="scope.row.activate"
                         class="ml-2"
                         inline-prompt
                         style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                         active-text="生效"
                         inactive-text="失效"
                         :active-value="1"
                         :inactive-value="0"
                         @change="activateChange($event === 1,scope.row.id)" /> -->
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>

  <!-- 仓库选择器组件 -->
  <ArchiveSelector v-model="warehouseSelectorVisible"
                   title="选择仓库"
                   :search-fields="warehouseSearchFields"
                   :table-columns="warehouseTableColumns"
                   :fetch-data-api="getWarehouseList"
                   :multiple="false"
                   @confirm="handleWarehouseSelect" />

  <!-- 项目选择器组件 -->
  <ArchiveSelector v-model="projectSelectorVisible"
                   title="选择项目"
                   :search-fields="projectSearchFields"
                   :table-columns="projectTableColumns"
                   :fetch-data-api="getProjectList"
                   :multiple="false"
                   @confirm="handleProjectSelect" />

  <!-- 自定义导出弹框 -->
  <el-dialog
    v-model="exportDialog.visible"
    title=""
    :width="680"
    custom-class="export-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
  >
    <template #header>
      <div class="export-dialog-header">
        <div class="header-left">
          <el-icon class="header-icon"><Setting /></el-icon>
          <div>
            <div class="header-title">自定义导出设置</div>
            <div class="header-subtitle">选择您需要导出的数据字段</div>
          </div>
        </div>
        <div class="selected-count">
          已选择 {{ selectedExportFields.length }} / {{ exportFieldList.length }} 项
        </div>
      </div>
    </template>
    
    <div class="export-content">
      <div class="export-toolbar">
        <div class="toolbar-left">
          <el-button 
            size="small" 
            type="primary" 
            @click="handleSelectAllFields(true)"
            :disabled="selectedExportFields.length === exportFieldList.length"
          >
            <el-icon><Switch /></el-icon>
            全选
          </el-button>
          <el-button 
            size="small" 
            @click="handleSelectAllFields(false)"
            :disabled="selectedExportFields.length === 0"
          >
            <el-icon><Refresh /></el-icon>
            清空
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-input
            v-model="fieldSearchText"
            size="small"
            placeholder="搜索字段..."
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      
      <div class="field-list-container">
        <div class="field-grid">
          <div 
            v-for="field in filteredExportFields" 
            :key="field.fieldName"
            class="field-card"
            :class="{ 'selected': selectedExportFields.includes(field.fieldName) }"
            @click="toggleField(field.fieldName)"
          >
            <div class="field-card-content">
              <el-checkbox 
                :model-value="selectedExportFields.includes(field.fieldName)"
                @change="() => toggleField(field.fieldName)"
                @click.stop=""
                class="field-checkbox"
              />
              <div class="field-info">
                <div class="field-name">{{ field.displayName }}</div>
                <div class="field-key">{{ field.fieldName }}</div>
              </div>
              <div class="field-icon">
                <el-icon v-if="selectedExportFields.includes(field.fieldName)" class="check-icon">
                  <Check />
                </el-icon>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="filteredExportFields.length === 0" class="empty-state">
          <el-icon class="empty-icon"><Search /></el-icon>
          <div class="empty-text">未找到匹配的字段</div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="export-footer">
        <div class="footer-info">
          <el-icon><InfoFilled /></el-icon>
          <span>将按当前查询条件导出选中字段的数据</span>
        </div>
        <div class="footer-buttons">
          <el-button @click="closeExportDialog" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="confirmCustomExport" 
            :loading="loading"
            size="large"
            :disabled="selectedExportFields.length === 0"
          >
            <el-icon><Download /></el-icon>
            导出 Excel
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>

  <!-- 批量复制弹窗 -->
  <el-dialog 
    v-model="batchCopyVisible" 
    title="批量复制软件核价方案" 
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="batch-copy-content">
      <el-alert
        title="提示"
        type="info"
        description="将选中的软件核价方案复制到指定的目标项目中，包含主数据、实施项和物料项。"
        :closable="false"
        style="margin-bottom: 20px"
      />
      
      <div class="copy-info">
        <p><strong>选中记录数：</strong>{{ selectedRows.length }} 条</p>
        <p><strong>源项目：</strong>{{ selectedRows.map(row => row.projectName).filter((name, index, arr) => arr.indexOf(name) === index).join(', ') }}</p>
      </div>
      
      <el-form label-width="120px" style="margin-top: 20px">
        <el-form-item label="目标项目" required>
          <el-input
            :value="selectedTargetProject?.name"
            placeholder="请选择目标项目"
            readonly
          >
            <template #append>
              <el-button @click="openTargetProjectSelector">选择项目</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeBatchCopyDialog">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmBatchCopy"
          :disabled="!selectedTargetProject"
        >
          确认复制
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 项目选择器 -->
  <ArchiveSelector
    v-model="projectSelectorVisible"
    title="选择项目"
    :fetch-data-api="getProjectList"
    :search-fields="projectSearchFields"
    :table-columns="projectTableColumns"
    @confirm="handleProjectSelect"
  />

  <!-- 目标项目选择器 -->
  <ArchiveSelector
    v-model="targetProjectSelectorVisible"
    title="选择目标项目"
    :fetch-data-api="getProjectList"
    :search-fields="projectSearchFields"
    :table-columns="projectTableColumns"
    @confirm="handleTargetProjectSelect"
  />
</template>

<style lang="scss" scoped>
.container {
  background: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 60px);
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
  
  .search-wrapper {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  // 搜索表单区域
  .search-form-section {
    .demo-form-inline {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: flex-end;
      
      .el-form-item {
        margin-bottom: 0;
        
        .el-input {
          border-radius: 8px;
          
          .el-input__wrapper {
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 8px;
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        &.search-buttons {
          .el-button {
            margin-right: 8px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            
            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            }
            
            &.search-btn {
              background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
              }
            }
            
            &.reset-btn {
              background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #F78989 0%, #F56C6C 100%);
              }
            }
          }
        }
      }
    }
  }
  
  // 操作按钮区域
  .action-buttons-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    
    .button-group {
      display: flex;
      gap: 10px;
      
      .el-button {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        &.add-btn {
          background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
          border: none;
          color: white;
          padding: 10px 20px;
          
          &:hover {
            background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
          }
        }
        
        &.template-btn {
          background: linear-gradient(135deg, #909399 0%, #B3B8C0 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #B3B8C0 0%, #909399 100%);
          }
        }
        
        &.import-btn {
          background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #F7BA2A 0%, #E6A23C 100%);
          }
        }
        
        &.export-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
          }
        }
        
        &.custom-export-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
          }
        }
      }
    }
    
    .primary-actions {
      // 主要操作按钮组
    }
    
    .secondary-actions {
      // 次要操作按钮组
    }
  }
}

.list-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: #f8fafc;
          color: #606266;
          font-weight: 600;
          border-bottom: 1px solid #e4e7ed;
        }
      }
    }
    
    .el-table__body-wrapper {
      .el-table__body {
        tr:hover {
          background-color: #f8fafc;
        }
        
        td {
          border-bottom: 1px solid #ebeef5;
        }
      }
    }
    
    .el-button {
      border-radius: 6px;
      
      &.el-button--small {
        padding: 5px 12px;
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  
  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 6px;
    }
    
    .btn-prev,
    .btn-next {
      border-radius: 6px;
    }
  }
}

/* 自定义导出弹窗样式 */
:deep(.export-dialog) {
  border-radius: 12px;
  overflow: hidden;
  
  .el-dialog__header {
    padding: 0;
    margin: 0;
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 0;
  }
}

.export-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 16px;
  // background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .header-icon {
      font-size: 28px;
      color: rgba(255, 255, 255, 0.9);
      background: rgba(255, 255, 255, 0.1);
      padding: 12px;
      border-radius: 50%;
      backdrop-filter: blur(10px);
    }
    
    .header-title {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 4px;
    }
    
    .header-subtitle {
      font-size: 14px;
      opacity: 0.8;
    }
  }
  
  .selected-count {
    background: rgba(255, 255, 255, 0.15);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
  }
}

.export-content {
  padding: 24px;
  
  .export-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    
    .toolbar-left {
      display: flex;
      gap: 8px;
      
      .el-button {
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
        }
      }
    }
  }
  
  .field-list-container {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    
    .field-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 12px;
      padding: 16px;
    }
    
    .field-card {
      border: 2px solid #e2e8f0;
      border-radius: 8px;
      padding: 16px;
      cursor: pointer;
      transition: all 0.3s;
      background: white;
      
      &:hover {
        border-color: #3b82f6;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
      }
      
      &.selected {
        border-color: #3b82f6;
        background: #eff6ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.25);
      }
      
      .field-card-content {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .field-checkbox {
          flex-shrink: 0;
        }
        
        .field-info {
          flex: 1;
          min-width: 0;
          
          .field-name {
            font-size: 15px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 4px;
            word-break: break-word;
          }
          
          .field-key {
            font-size: 12px;
            color: #64748b;
            font-family: 'Monaco', 'Consolas', monospace;
            background: #f1f5f9;
            padding: 2px 6px;
            border-radius: 4px;
            word-break: break-all;
          }
        }
        
        .field-icon {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .check-icon {
            color: #22c55e;
            font-size: 18px;
            animation: checkIn 0.3s ease-out;
          }
        }
      }
    }
    
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px;
      color: #64748b;
      
      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.5;
      }
      
      .empty-text {
        font-size: 16px;
      }
    }
  }
}

.export-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
  
  .footer-info {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #64748b;
    font-size: 14px;
    
    .el-icon {
      color: #3b82f6;
    }
  }
  
  .footer-buttons {
    display: flex;
    gap: 12px;
    
    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 12px 24px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }
      
      &.el-button--primary {
        // background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        
        &:hover {
          opacity: 0.9;
        }
        
        &:disabled {
          background: #e2e8f0;
          color: #94a3b8;
          transform: none;
          box-shadow: none;
        }
      }
      
      .el-icon {
        margin-right: 6px;
      }
    }
  }
}

@keyframes checkIn {
  0% {
    transform: scale(0) rotate(180deg);
    opacity: 0;
  }
  100% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
}

/* 自定义导出按钮样式 */
.custom-export-btn {
  background: linear-gradient(135deg, #409EFF, #1989fa);
  border: none;
  
  &:hover {
    opacity: 0.9;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }
}

/* 批量复制弹窗样式 */
.batch-copy-content {
  .copy-info {
    background: #f8fafc;
    padding: 16px;
    border-radius: 8px;
    margin: 16px 0;
    
    p {
      margin: 8px 0;
      color: #606266;
      
      strong {
        color: #303133;
      }
    }
  }
}
</style>
